package com.yql.common.utils;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @Author: huweixing
 * @ClassName: MapSortUtil
 * @Description: map键值对排序工具类
 * @Date: 2021-03-26
 * @Time: 13:17
 **/
public class MapSortUtil {

    public static Map<String, String> sortMapByValuesASC(Map<String, String> map) {
        Map<String, String> sortedMap = new LinkedHashMap<>();
        map.entrySet().stream()
                .sorted(Map.Entry.comparingByValue())
                .forEachOrdered(x -> sortedMap.put(x.getKey(), x.getValue()));
        return sortedMap;
    }

    public static Map<String, String> sortMapByValuesDESC(Map<String, String> map) {
        Map<String, String> sortedMap = new LinkedHashMap<>();
        map.entrySet().stream()
                .sorted(Collections.reverseOrder(Map.Entry.comparingByValue()))
                .forEachOrdered(x -> sortedMap.put(x.getKey(), x.getValue()));
        return sortedMap;
    }

    public static Map<String, String> sortMapByKeysASC(Map<String, String> map) {
        Map<String, String> sortedMap = new LinkedHashMap<>();
        map.entrySet().stream()
                .sorted(Map.Entry.comparingByKey())
                .forEachOrdered(x -> sortedMap.put(x.getKey(), x.getValue()));
        return sortedMap;
    }

    public static Map<String, String> sortMapByKeysDESC(Map<String, String> map) {
        Map<String, String> sortedMap = new LinkedHashMap<>();
        map.entrySet().stream()
                .sorted(Collections.reverseOrder(Map.Entry.comparingByKey()))
                .forEachOrdered(x -> sortedMap.put(x.getKey(), x.getValue()));
        return sortedMap;
    }

    public static <K extends Comparable, V extends Comparable> Map<K, V> sortMapByValues(Map<K, V> aMap) {
        HashMap<K, V> finalOut = new LinkedHashMap<>();
        aMap.entrySet()
                .stream()
                .sorted((p1, p2) -> p2.getValue().compareTo(p1.getValue()))
                .collect(Collectors.toList()).forEach(ele -> finalOut.put(ele.getKey(), ele.getValue()));
        return finalOut;

    }


}
